<?php

namespace support;

use app\services\TransferService;
use GuzzleHttp\Client;
use plugin\admin\app\model\RequestLog;
use plugin\admin\app\model\TransferJob;

class JRTools
{
    public static function transfer($jobId)
    {
        $client = new Client();

        $job = TransferJob::where('id', $jobId)->first();
        if (!$job) {
            echo "任务不存在\n";
            return;
        }

        $params = json_decode($job['params'], true);


        $jsonData = [
            "name" => $params['name'],
            "manufacturer" => $params['brand_name'],
            "beamType" => $params['light_type'],
            "displayName" => $params['display_name'],
            'needTypes' => $params['selected_formats'],
            'language' => $params['language'] ?? '中文',
        ];

        $otherParams = json_decode($job['after_edit_result'], true);

        $jsonData['attributes'] = $otherParams['attributes'];
        $jsonData['macros'] = $otherParams['macros'];

        try {
            $response = $client->post(getenv('TOOLS_API_URL'), [
                'headers' => [
                    'Content-Type' => 'application/json'
                ],
                'body' => json_encode($jsonData)
            ]);

            $statusCode = $response->getStatusCode();
            $responseBody = $response->getBody()->getContents();
        } catch (\Exception $e) {
            echo "请求失败: " . $e->getMessage() . $e->getTraceAsString() . "\n";
            $job->status = TransferJob::EXECUTE_FAILED;
            $job->fail_reason = $e->getMessage() . $e->getTraceAsString();
            $job->save();

            RequestLog::insert([
                'job_id' => $job['id'],
                'request' => json_encode($jsonData, JSON_UNESCAPED_UNICODE),
                'response' => '',
                'created_time' => date('Y-m-d H:i:s')
            ]);

            TransferService::sendJobMessage($jobId, '文件转换失败', 100, 400);
            return;
        }


        if ($statusCode == 200) {

            $responseBody = json_decode($responseBody, true);

            if ($responseBody['code'] == 0) {
                RequestLog::insert([
                    'job_id' => $job['id'],
                    'request' => json_encode($jsonData, JSON_UNESCAPED_UNICODE),
                    'response' => json_encode($responseBody, JSON_UNESCAPED_UNICODE),
                    'created_time' => date('Y-m-d H:i:s')
                ]);

                $job->download_url = $responseBody['url'];
                $job->save();

                TransferService::sendJobMessage($jobId, '文件转换成功', 100, 200);
            } else {
                $job->status = TransferJob::EXECUTE_FAILED;
                $job->fail_reason = $responseBody['msg'] ?? '未知错误';
                $job->save();

                TransferService::sendJobMessage($jobId, '文件转换失败', 100, 400);
            }



            return $responseBody;
        } else {
            echo "请求失败: " . $statusCode . "\n";
            $job->status = TransferJob::EXECUTE_FAILED;
            $job->save();

            TransferService::sendJobMessage($jobId, '文件转换失败', 100, 400);
        }

    }
}